package TestDemo6;

import java.util.concurrent.*;


public class Test1 {
    public static void main(String[] args) {
        ExecutorService executorService1 = Executors.newCachedThreadPool();


        for (int i = 0; i < 10; i++) {
            int id = i;
            executorService1.submit(()-> {
               Thread t=   Thread.currentThread();
                System.out.println(" 当前线程名为: " + t.getName() + " id为  "+  id);
            });
        }

//        结束所有线程
        executorService1.shutdown();
    }
}




class MyPoolThread {



    // 用一个阻塞队列来存储工作任务
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    public MyPoolThread(int nThreads) {

        for (int i = 0; i < nThreads; i++) {


//            实例化线程
            Thread thread = new Thread(()->{

                // 使用while 的方式让 n 个线程都存在
//                    并且进行抢占执行
//                while(true) {
                    try {
                        Runnable t  = queue.take();
                        t.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
//                }
            });

            // 创建线程
            thread.start();

        }
    }

   public  void  mySubmit(Runnable runnable) {
        // 添加任务
       try {
           queue.put(runnable);
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       }
   }
    public static void main(String[] args) {
        MyPoolThread t = new MyPoolThread(5);

        // 重写任务
        t.mySubmit(()->{
            for (int i = 0; i < 10; i++) {
                int id = i;
                t.mySubmit(()-> {
                    Thread t1 =   Thread.currentThread();
                    System.out.println(" 当前线程名为: " + t1.getName() + " id为  "+  id);
                });
            }
        });
    }

}